package team.pwy.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayResponse;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import team.pwy.GameLeaderboard;
import team.pwy.config.AlipayTicketConfig;
import team.pwy.consts.RbmConsts;
import team.pwy.mapper.MovieMapper;
import team.pwy.pojo.entity.Movie;
import team.pwy.pojo.entity.Order;
import team.pwy.pojo.entity.TicketOrder;
import team.pwy.service.*;
import team.pwy.vo.Result;

import java.io.UnsupportedEncodingException;
import java.util.List;

@RestController
@RequestMapping("alipay")
public class AlipayTicketController {

    @Resource
    private TicketService ticketService;

    @Resource
    private OrderService orderService;

    @Resource
    private MovieService movieService;

    @Resource
    private MovieMapper movieMapper;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private WebSocketProcess webSocketProcess;

    @GetMapping("/payTicket")
    @ResponseBody
    public String pay(Integer userId, String orderNum, String price, String time, HttpServletRequest request) {
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayTicketConfig.gatewayUrl, AlipayTicketConfig.app_id, AlipayTicketConfig.merchant_private_key, "json", AlipayTicketConfig.charset, AlipayTicketConfig.alipay_public_key, AlipayTicketConfig.sign_type);
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayTicketConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayTicketConfig.notify_url);
        String timeout_express = "15m";
        if (time != null && time.length() > 0) {
            timeout_express = time + "s";
        }

        String body = "";
        SnowFlake snowFlake1 = new SnowFlake(2, 5);
        String out_request_no = String.valueOf(snowFlake1.nextId());

        String out_trade_no = orderNum;
        String total_amount = price;
        String subject = "票无忧影城影票";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\"" + timeout_express + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String payResult = null;
        try {
            AlipayResponse alipayResponse = alipayClient.pageExecute(alipayRequest);
            // getBody() 支付后，支付宝返回的支付的信息
            payResult = alipayResponse.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        ticketService.addTicOrd(userId, orderNum, price, out_request_no);
        // 生成订单

        return payResult;
    }

    // 支付后的 获得 支付宝的信息 payResult --->request
    @RequestMapping("alipayTicketReturnNotice")
    public String alipayNotifyNotice(HttpServletRequest request) throws UnsupportedEncodingException {
        System.out.println("异步请求，支付成功后，支付宝的返回数据是：" + request);
        // 商户订单号
        String orderNum = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        //支付宝交易号
        String tradeNo = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
        // 付款金额
        String payPrice = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

        // 支付成功
        // 查询订单号
        Order order = orderService.findByNumber(orderNum);
        ticketService.updateByOrdNum(orderNum, tradeNo);
        // 更改订单状态
        orderService.updateById(order.getId(), 1);
        GameLeaderboard leaderboard = new GameLeaderboard();

        Movie movie = movieService.findById(order.getMovieId());
        // 刷新redis排行旁
        leaderboard.updateScore(movie.getId() + "&" + movie.getTitle() + "&" + movie.getPosterImg(), movie.getPrice() * order.getQuota());
        movieMapper.updateGrossed(order.getQuota() * order.getMoviePrice(), order.getMovieId());

        ticketService.updateByOrdNum(orderNum, tradeNo);
        List<Integer> allSelectSeatId = orderService.findByOrderId(order.getId());
        if (allSelectSeatId != null && !allSelectSeatId.isEmpty()) {
            for (Integer selectSeatId : allSelectSeatId) {
                try {
                    webSocketProcess.sendAllMessage(order.getUserId(), selectSeatId, 2);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }

        // 发送支付成功RabbitMQ队列
        rabbitTemplate.convertAndSend(RbmConsts.ORDER_SUCCESS, order.getId());
        return "success";
    }

    @RequestMapping("refund")
    public Result returnPay(String orderNum) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayTicketConfig.gatewayUrl, AlipayTicketConfig.app_id, AlipayTicketConfig.merchant_private_key, "json", AlipayTicketConfig.charset, AlipayTicketConfig.alipay_public_key, AlipayTicketConfig.sign_type);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();

        TicketOrder ticketOrder = ticketService.findByOrderNum(orderNum);

        bizContent.put("trade_no", ticketOrder.getTradeNo());
        bizContent.put("refund_amount", ticketOrder.getOrderPrice());
        bizContent.put("out_request_no", ticketOrder.getOutRequestNo());

        request.setBizContent(bizContent.toString());

        AlipayTradeRefundResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            // 退款
            orderService.updateByNum(orderNum);
            ticketService.updateByON(orderNum);
            return new Result("200", "已退款");
        } else {
            return new Result("500", "退款失败请重新尝试");
        }
    }


    @GetMapping("/conPayTicket")
    @ResponseBody
    public String payContinue(String orderNum, HttpServletRequest request) {
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayTicketConfig.gatewayUrl, AlipayTicketConfig.app_id, AlipayTicketConfig.merchant_private_key, "json", AlipayTicketConfig.charset, AlipayTicketConfig.alipay_public_key, AlipayTicketConfig.sign_type);
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayTicketConfig.return_url_con);
        alipayRequest.setNotifyUrl(AlipayTicketConfig.notify_url);


        TicketOrder ticketOrder = ticketService.findByOrderNum(orderNum);

        String timeout_express = "15m";

        String body = "";
        String out_trade_no = orderNum;
        String total_amount = String.valueOf(ticketOrder.getOrderPrice());
        String subject = "票无忧影城影票";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\"" + timeout_express + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String payResult = null;
        try {
            AlipayResponse alipayResponse = alipayClient.pageExecute(alipayRequest);
            // getBody() 支付后，支付宝返回的支付的信息
            payResult = alipayResponse.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return payResult;
    }

}
